#! /usr/bin/python3
# -*- coding: UTF-8 -*-
  
'''※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
File Name: city_code.py
Author: GID5564
Description: 根据城市名称获取csv中的区划代码
Version: 1.0
Created Time: 16/09/24-15:58:06
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※'''

import pandas as pd
import re

# 匹配 City_ID 中的数字
def convert(x):
    pat = re.compile('(\d+)')
    return pat.search(x).group()

# 建立城市与代码之间的映射关系
def city2id(file):
    code_dict = {}
    key = 'City_CN'
    value = 'City_ID_map'
    for k, v in zip(file[key], file[value]):
        code_dict[k] = v
    return code_dict
#通过城市名称查询其代码并返回   
def query_code(table, city):
    '''
    table:字典 
    city:字符串
    '''
    try:
        code = table[city]
    except KeyError:
        raise 
    return code
    
class CityCode():
    def get_city_code1(self, city_name, csvfile):
        """
        根据城市名称从CSV文件中获取城市代码。
        
        参数：
        city_name (str): 需要查询的城市名称。
        csvfile (str): 包含城市名称和代码的CSV文件路径。
        
        返回：
        int: 对应城市名称的城市代码，如果未找到则返回None。
        """
        file = pd.read_csv(csvfile, usecols=['name', 'code'])
        city_id_map = dict(zip(file['name'], file['code']))
        return city_id_map.get(city_name)

    def get_city_code2(self,city,filename):
        file = pd.read_csv(filename)
        # 选取需要的两列信息
        file = file.loc[:,['City_ID', 'City_CN']]
        # 城市与代码组成字典
        file['City_ID_map'] = file['City_ID'].map(convert)
        code_dict = city2id(file)
        # 城市代码
        code=query_code(code_dict,city)
        return code

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        